package com.imooc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class CorsConfig {
    
    public CorsConfig() {}

    @Bean
    public CorsFilter corsFilter() {

        // 1. 添加 cors 配置信息
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("http://localhost:8080");

        // 2, 设置发送cookie 信息
        config.setAllowCredentials(true);

        // 3. 设置允许请求的方式
        config.addAllowedMethod("*");

        // 4. 设置允许的header
        config.addAllowedHeader("*");

        // 5. 为 URL 添加映射路径

        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**", config);

        return new CorsFilter(configurationSource);
    }
    
}
